import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class Homework_UdpEchoServer {
    private DatagramSocket socket = null;
    public Homework_UdpEchoServer(int port) throws SocketException {
        //需要手动指定端口号
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动！");
        while(true){
            //1.等待接收客户端请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            //2.处理客户端请求 计算响应
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    response.getBytes().length, requestPacket.getSocketAddress());
            //3.发送响应
            socket.send(responsePacket);
            //4.打印请求和响应信息
            System.out.printf("[%s:%d] req=%s, resp=%s\n",
                    requestPacket.getAddress().toString(), requestPacket.getPort(), request, response);
        }
    }
    public String process(String request){
        //因为是回显服务器，因此直接返回请求即可
        return request;
    }

    public static void main(String[] args) throws IOException {
        Homework_UdpEchoServer server = new Homework_UdpEchoServer(9999);
        server.start();
    }
}
